import time
from odoo import api, models, _

from datetime import datetime
from dateutil.relativedelta import relativedelta


class AccountingReport(models.TransientModel):
    _inherit = "accounting.report"

    @api.model
    def report_print(self, values, callback):
        # callback(values )
        # print('-----report_print, value,', values)

        balancesheet_account_report_id = self.env.ref(
            'accounting_pdf_reports.account_financial_report_balancesheet0')

        if values.get('account_report_id') != balancesheet_account_report_id.id:
            return callback(values)

        date_from = values.get('date_from')

        date_to_open = datetime.strptime(
            date_from, '%Y-%m-%d') + relativedelta(days=-1)
        date_to_open = date_to_open.strftime('%Y-%m-%d')

        values_open = values.copy()
        values_open['date_from'] = None
        values_open['date_to'] = date_to_open

        # print('values_open', values_open)
        res_open = callback(values_open)

        values_close = values.copy()
        values_close['date_from'] = None
        # print('values_close', values_close)

        res_close = callback(values_close)
        res_delta = callback(values)

        # print('res_open', res_open)
        # print('res_close', res_close)
        # print('res_delta', res_delta)

        key_names = {
            'report,sum,Balance Sheet': {'name2': '总计', 'type2': 'sum'},

            'report,account_type,Assets': {'name2': '资产', 'type2': 'assets'},
            'report,account_type,Assets,accounts': {'name2': '', 'type2': 'assets'},

            'report,sum,Liability': {'name2': '负债及权益', 'type2': 'liability'},

            'report,account_type,Liability': {'name2': '负债', 'type2': 'liability'},
            'report,account_type,Liability,accounts': {'name2': '', 'type2': 'liability'},

            'report,sum,Equity': {'name2': '权益', 'type2': 'liability'},
            'report,account_type,Equity': {'name2': '权益', 'type2': 'liability'},
            'report,account_type,Equity,accounts': {'name2': '', 'type2': 'liability'},
            'report,account_report,Profit (Loss) to report': {'name2': '利润', 'type2': 'liability'},

            'step': 'report,sum,Balance Sheet'
        }

        def to_dict(res):
            result = dict((key, {}) for key in key_names.keys())
            for line in res.get('get_account_lines'):
                full_name = '%s,%s,%s' % (
                    line['type'], line['account_type'], line['name'])

                if full_name in result.keys():
                    result['step'] = full_name
                    result[full_name] = line
                else:
                    step = result['step']
                    accounts = result[step + ',accounts']
                    accounts[line['name'][0:6]] = line

            return result

        dict_open = to_dict(res_open)
        dict_close = to_dict(res_close)
        dict_delta = to_dict(res_delta)

        # print('values_open---,',  values_open)
        # print('res_open---,',  res_open)
        # print('dict_open---,', dict_open)
        # print('res_close---,',  res_close)
        # print('dict_close---,', dict_close)
        # print('res_delta---,',  res_delta)
        # print('dict_delta---,', dict_delta)

        def merge_sum(name):
            open1 = dict_open[name]
            close = dict_close[name]
            delta = dict_delta[name]

            debit_open = open1['balance'] > 0 and open1['balance'] or 0
            credit_open = open1['balance'] < 0 and -open1['balance'] or 0
            debit_close = close['balance'] > 0 and close['balance'] or 0
            credit_close = close['balance'] < 0 and -close['balance'] or 0

            return {
                'name2': key_names[name]['name2'],
                'type2': key_names[name]['type2'],
                'name': open1['name'],
                'type': open1['type'],
                'account_type': open1['account_type'],
                'level': open1['level'],

                'debit_open': debit_open,
                'credit_open': credit_open,
                'debit': delta['debit'],
                'credit':  delta['credit'],
                'balance':  delta['balance'],
                'debit_close': debit_close,
                'credit_close': credit_close,

            }

        def merge_account(name_src):
            name = name_src + ',accounts'
            open1 = dict_open.get(name, {})
            close = dict_close.get(name, {})
            delta = dict_delta.get(name, {})

            keys = list(open1.keys()) + list(close.keys()) + list(delta.keys())
            keys = list(set(keys))
            keys.sort()

            def fn1(k):
                c3 = close[k]
                c3_bal = c3['balance']
                o3_bal = open1.get(k, {'balance': 0})['balance']
                d3 = delta.get(k, {'debit': 0, 'credit': 0})
                return {
                    'name2': c3['name'],
                    'type2': key_names[name_src]['type2'],
                    'name': c3['name'],
                    'type': c3['type'],
                    'account_type': c3['account_type'],
                    'level': c3['level'],
                    'debit_open': o3_bal > 0 and o3_bal or 0,
                    'credit_open': o3_bal < 0 and -o3_bal or 0,
                    'debit': d3['debit'],
                    'credit':  d3['credit'],
                    'debit_close': c3_bal > 0 and c3_bal or 0,
                    'credit_close': c3_bal < 0 and -c3_bal or 0,
                }

            return [fn1(k) for k in keys]

            # 'report,sum,Balance Sheet': {},
            # 'report,account_type,Assets': {},
            # 'report,account_type,Assets,accounts': {},

            # 'report,sum,Liability': {},
            # 'report,account_type,Liability': {},
            # 'report,account_type,Liability,accounts': {},

            # 'report,account_report,Profit (Loss) to report': {},

        assets_accounts = 'report,account_type,Assets'
        liability_accounts = 'report,account_type,Liability'

        res_list = []
        # res_list.append(merge_bal())
        res_list.append(merge_sum('report,account_type,Assets'))
        res_list = res_list + merge_account(assets_accounts)
        res_list.append(merge_sum('report,sum,Liability'))
        res_list.append(merge_sum('report,account_type,Liability'))
        res_list = res_list + merge_account(liability_accounts)
        res_list.append(merge_sum('report,sum,Equity'))
        # res_list.append(merge_sum('report,account_type,Equity'))
        res_list = res_list + merge_account('report,account_type,Equity')
        res_list.append(
            merge_sum('report,account_report,Profit (Loss) to report'))

        res_ret = res_delta.copy()
        res_ret['get_account_lines'] = res_list
        # print('res_ret--------', res_ret)
        return res_ret
